package com.wecloud.core.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.wecloud.core.action.impl.BaseTransAction;
import com.wecloud.core.action.impl.BaseTransCfmAction;
import com.wecloud.core.constant.ErrorMsg;
import com.wecloud.core.constant.WeContext;
import com.wecloud.core.data.jnlservice.ConsoleLogJnlService;
import com.wecloud.core.exception.WeException;
import com.wecloud.core.server.InitContext;
import com.wecloud.core.utils.GenarateSeqUtil;
import com.wecloud.core.utils.JsonUtils;

@RestController
public class WeCloudMainConller extends WeCloudCoreConller {
	@Autowired
	private InitContext initContext;
	@Autowired
	private ConsoleLogJnlService service;

	Logger logger = LoggerFactory.getLogger(WeCloudMainConller.class);

	@Override
	@RequestMapping(value = "wecloud/**", method = RequestMethod.POST)
	@SuppressWarnings({ "unchecked", "rawtypes" })
	protected void handler(HttpServletRequest req, HttpServletResponse resp) {
		// 初始化context
		WeContext context = null;
		Map logMap = new HashMap();
		try {
			context = initContext.init(req, resp);
			if (context == null) {
				throw new WeException(ErrorMsg.Error_9997);
			} else if (context.getUser() != null) {
				logMap.put("oprationUserid", context.getUser().getUserId());
			}
			
			if (context.getTransactionId() == null || "".equals(context.getTransactionId())) {
				throw new WeException(ErrorMsg.Error_9998);
			}
			logMap.put("conid", GenarateSeqUtil.genarateUUID());
			logMap.put("transid", context.getTransactionId());
			logMap.put("params", context.getData("reqParam"));
			logMap.put("status", "R");// R待处理;E错误;S成功;
			logMap.put("oprationTm", new Date());
			context.setData("conid", logMap.get("conid"));
			service.SaveConsoleLogInfo(logMap);
			Object obj = getTransAction(context.getTransactionId());
			if (obj instanceof BaseTransAction) {
				((BaseTransAction) obj).prepare(context);
				((BaseTransAction) obj).excute(context);
			}
			if (obj instanceof BaseTransCfmAction) {
				((BaseTransCfmAction) obj).confirm(context);
				((BaseTransCfmAction) obj).prepare(context);
				((BaseTransCfmAction) obj).excute(context);
				((BaseTransCfmAction) obj).after(context);
			}
			context.setResponse("code", ErrorMsg.Error_0000.getRtnCode());
			context.setResponse("message", ErrorMsg.Error_0000.getDesc());
			context.setResponse("content", context.getData("content"));
			String rtn = JsonUtils.serialize(context.getResponse());
			responseMsg(rtn, resp);
			logMap.put("status", "S");
			logMap.put("response", rtn);
			logMap.put("endTm", new Date());
			service.UpdateConsoleLogInfo(logMap);
			logger.info("[请求处理结束]：["+context.getString("uri")+"],返回参数："+rtn+",返回时间："
					+new Date());
		} catch (WeException e) {
			logger.error("[wecloud sys has an Exception]-->", e);
			Map map = new HashMap();
			map.put("code", e.getCode());
			map.put("message", e.getMsg());
			String str = JsonUtils.serialize(map);
			responseMsg(str, resp);
			logMap.put("status", "E");
			logMap.put("response", str);
			logMap.put("reason", e.getMsg()); 
			logMap.put("endTm", new Date());
			service.UpdateConsoleLogInfo(logMap);
		} catch (Throwable e) {
			logger.error("[wecloud sys has an Exception]-->", e);
			Map map = new HashMap();
			map.put("code", ErrorMsg.Error_9999.getRtnCode());
			map.put("message", ErrorMsg.Error_9999.getDesc());
			String str = JsonUtils.serialize(map);
			responseMsg(str, resp);
			logMap.put("status", "E");
			logMap.put("response", str);
			logMap.put("endTm", new Date());
			logMap.put("reason", e.getMessage());
			service.UpdateConsoleLogInfo(logMap);
		}
	}
}
